//
//  MySaveViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/31.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "MySaveViewController.h"
#import "MySaveModel.h"
#import "homeVCCell.h"
#import "AlertMessageView.h"
#import "ProductDetailsViewController.h"
#import "OrderNullView.h"
#import "EditHUDView.h"
@interface MySaveViewController (){
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    int Page;
    UITableViewCellEditingStyle selectEditingStyle;
    UIButton *allButton;
    BOOL editTable;
    NSTimer *timer_;
}
@property (nonatomic,strong)NSMutableArray *selectedDic;
@property (nonatomic,strong)NSMutableArray *selectedArr;
@property (nonatomic,strong)NSMutableArray *fakeData;
@end

@implementation MySaveViewController
@synthesize selectedDic,selectedArr,fakeData;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.leftBtn addTarget: self action: @selector(goBackAction) forControlEvents: UIControlEventTouchUpInside];
    self.title = @"我的收藏";
    [self.view setBackgroundColor:UIColorFromRGB(0xf3f2f2)];
//    [self createNullView];
    OrderNullView *orderView = [[OrderNullView alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, SHEIGHT-108)];
    [orderView setBackgroundColor:[UIColor clearColor]];
    orderView.tag = 101;
    [orderView setHidden:YES];
    [self.view addSubview:orderView];
    
    AlertMessageView *messageView = [[AlertMessageView alloc]initWithFrame:CGRectMake(0, 0, SWIDTH, 25)];
    messageView.backgroundColor = GREENColor;
    messageView.tempLab.font = [UIFont systemFontOfSize:12];
    messageView.tag = 101;
    [self.mainView addSubview:messageView];
    [self.rightBtn setTitle:@"编辑" forState:0];
    self.rightBtn.selected = NO;
    [self.rightBtn addTarget:self action:@selector(editClick:) forControlEvents:UIControlEventTouchUpInside];
    editTable = NO;
    self.selectedDic = [NSMutableArray array];
    self.selectedArr = [NSMutableArray array];
    self.fakeData = [NSMutableArray array];
    allButton = [UIButton buttonWithType:0];
    allButton.frame = CGRectMake(0, VHEIGHT - 44, SWIDTH, 44);
    allButton.backgroundColor = REDColor;
    allButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [allButton setTitle:@"删除收藏" forState:0];
    [allButton setTitleColor:[UIColor whiteColor] forState:0];
    [allButton addTarget:self action:@selector(removeAllData:) forControlEvents:UIControlEventTouchUpInside];
    [allButton setHidden:YES];
    [self.mainView addSubview:allButton];

    UITableView *tempTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 25, SWIDTH, VHEIGHT-25)];
    [tempTableView setBackgroundColor:UIColorFromRGB(0xf3f2f2)];
    [tempTableView setDelegate:self];
    [tempTableView setDataSource:self];
    UIView *theView = [[UIView alloc] initWithFrame:self.mainTableView.frame];
    [theView setBackgroundColor:[UIColor clearColor]];
    self.mainTableView.separatorStyle = NO;
    self.mainTableView = tempTableView;
    [self.mainTableView setBackgroundView:theView];
    [self.mainView addSubview:self.mainTableView];
    self.rightBtn.selected = NO;
    [self.mainTableView setEditing:NO animated:YES];
    self.mainTableView.allowsMultipleSelectionDuringEditing = NO;
    self.mainTableView.tableFooterView=[[UIView alloc]init];
    [self addHeader];
    [self addFooter];
    // Do any additional setup after loading the view.
}
-(void)editClick:(UIButton *)sender{
    if (self.rightBtn.selected == NO) {
        editTable = YES;
        [self.rightBtn setTitle:@"取消" forState:0];
        self.rightBtn.selected = YES;
        self.mainTableView.allowsMultipleSelectionDuringEditing = YES;
        [self.mainTableView setEditing:YES animated:YES];
        self.mainTableView.frame = CGRectMake(0, 25, SWIDTH, VHEIGHT-44-25);
        [allButton setHidden:NO];
    }else{
        editTable = NO;
        [self.rightBtn setTitle:@"编辑" forState:0];
        self.rightBtn.selected  = NO;
        [allButton setHidden:YES];
        self.mainTableView.allowsMultipleSelectionDuringEditing = NO;
        [self.mainTableView setEditing:NO animated:YES];
        self.mainTableView.frame = CGRectMake(0, 25, SWIDTH, VHEIGHT-25);
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mainTableView reloadData];
        });
    });
}
-(void)removeAllData:(UIButton *)sender{
    if ([self.selectedDic count] > 0 ) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定要删除选中的收藏信息吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除收藏", nil];
        alert.tag = 304;
        [alert show];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请选择要删除的收藏信息!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"重新选择", nil];
        alert.tag = 303;
        [alert show];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 303) {
        if (buttonIndex == alertView.cancelButtonIndex) {
            if (self.rightBtn.selected == YES) {
                self.rightBtn.selected  = NO;
                [self.rightBtn setTitle:@"编辑" forState:0];
                [allButton setHidden:YES];
                [self.mainTableView setEditing:NO animated:YES];
                self.mainTableView.allowsMultipleSelectionDuringEditing = NO;
                self.mainTableView.frame = CGRectMake(0, 0, SWIDTH, VHEIGHT);
            }
        }
    }else if (alertView.tag == 304){
        if (buttonIndex == alertView.cancelButtonIndex) {
            return;
        }else{
            [self delFavor];
            //TODO:删除收藏信息
        }
    }
}
-(void)delFavor{
    TIME
    HEADDIC(nowTime, DELFAVOR);
    NSMutableDictionary *body = [NSMutableDictionary dictionary];
    NSMutableArray *ids = [NSMutableArray array];
    for (int i = 0; i < [selectedArr count]; i++) {
        homeModelSupply *dic = [self.selectedArr objectAtIndex:i];
        NSMutableDictionary *head = [NSMutableDictionary dictionary];
        [head setObject:dic.home_id forKey:@"supply_id"];
        [head setObject:dic.material_id forKey:@"material_id"];
        [ids addObject:head];
    }
    
    [body setObject:ids forKey:@"ids"];
    NSString *result1 = [Unity requestSomeApiData:HEAD withBody:body];
    NSMutableDictionary *json = [result1 objectFromJSONString];
    if ([[json objectForKey:@"err_code"] integerValue]==0) {
        //        NSMutableDictionary *data = [json objectForKey:@"data"];
        for (int i = 0; i < [selectedArr count]; i++) {
            homeModelSupply *dic = [self.selectedArr objectAtIndex:i];
            [self.fakeData removeObject:dic];
        }
        [self.selectedArr removeAllObjects];
        [self.selectedDic removeAllObjects];
        [self.mainTableView reloadData];
        [self.mainTableView deleteRowsAtIndexPaths:self.selectedDic withRowAnimation:UITableViewRowAnimationFade];
        self.rightBtn.selected = NO;
        [self.rightBtn setTitle:@"编辑" forState:0];
        [allButton setHidden:YES];
        editTable = NO;
        self.mainTableView.allowsMultipleSelectionDuringEditing = NO;
        [self.mainTableView setEditing:NO animated:YES];
        self.mainTableView.frame = CGRectMake(0, 0, SWIDTH, VHEIGHT);
        
        EditHUDView *hudView = [[EditHUDView alloc]initWithFrame:CGRectMake(0, 64, SWIDTH, VHEIGHT)];
        hudView.backgroundColor = [UIColor clearColor];
        hudView.tag = 1010;
        hudView.alertLab.text = @"删除成功";
        [self.view addSubview:hudView];
        timer_ = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(doTime) userInfo:nil repeats:NO];
    }else{
        SHOW_TITLEALERT(@"提示", [json objectForKey:@"err_message"]);
    }
}
-(void)doTime
{
    //alert过1秒自动消失
    [self resetTimer];
    [self removeHudView];
}
-(void)removeHudView{
    EditHUDView *hudView = (EditHUDView *)[self.view viewWithTag:1010];
    if (hudView) {
        [hudView removeFromSuperview];
        hudView = nil;
    }
}
-(void) resetTimer
{
    if (timer_) {
        [timer_ invalidate];
        timer_ = nil;
    }
}
-(void)createNullView{
    UIView *view = [self createViewFrame:CGRectMake(0, 0, SWIDTH, VHEIGHT) bgColor:[UIColor clearColor] tag:900];
    [view setHidden:YES];
    [self.mainView addSubview:view];
    UIImageView *imageView = [self createImageViewFrame:CGRectMake((SWIDTH - 62)/2, (VHEIGHT - 55)/2, 62, 55) image:nil imageName:@"暂无收藏" tag:0];
    [view addSubview:imageView];
    
    UILabel *textLab = [self createLabelFrame:CGRectMake(0, (VHEIGHT - 55)/2 + 65, SWIDTH, 14) title:@"这里空空如也～" titleColor:UIColorFromRGB(0xdedede) tag:0];
    textLab.textAlignment = NSTextAlignmentCenter;
    [view addSubview:textLab];
}
-(void)saveString{
    AlertMessageView *messageView = (AlertMessageView *)[self.mainView viewWithTag:101];
        UIView *view = (UIView *)[self.mainView viewWithTag:900];
    if ([self.fakeData count]==0) {
        [self.rightBtn setTitle:@"" forState:0];
        [messageView setHidden:YES];
        [self.mainTableView setHidden:YES];
        [view setHidden:NO];
    }else{
        [self.rightBtn setTitle:@"编辑" forState:0];
        [self.mainTableView setHidden:NO];
        [messageView setHidden:NO];
        [view setHidden:YES];
    }
    NSString *str = [NSString stringWithFormat:@"共收藏%ld个货源",[self.fakeData count]];
    messageView.tempLab.text = str;
}

-(void)requestPage:(int)page{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        TIME
        HEADDIC(nowTime, MYFOVOR);
        NSMutableDictionary *body = [NSMutableDictionary dictionary];
        [body setObject:[NSNumber numberWithInt:page] forKey:@"page"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:HEAD forKey:@"head"];
        [dic setObject:body forKey:@"body"];
        NSString *result = [Unity requestSomeApiData:HEAD withBody:body];
        NSLog(@"result___%@",result);
        MySaveModel *model = [[MySaveModel alloc]init];
        NSMutableArray *arr = [NSMutableArray array];
        if ([[dic objectForKey:@"err_code"] integerValue] == 0) {
            [model parseResponseData:result];
            arr = model.list;
        }
        if ([arr count]!=0) {
            if (page == 1) {
                [self.fakeData removeAllObjects];
            }
            
            [self.mainTableView setHidden:NO];
            [self.fakeData addObjectsFromArray:arr];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新界面
            OrderNullView *orderView = (OrderNullView *)[self.view viewWithTag:101];
            if ([self.fakeData count]==0) {
                [orderView setHidden:NO];
                [self.mainTableView setHidden:YES];
                [self.rightBtn setTitle:@"" forState:0];
            }else{
                if (editTable) {
                    [self.rightBtn setTitle:@"取消" forState:0];
                }else{
                    [self.rightBtn setTitle:@"编辑" forState:0];
                }
            }
            [self saveString];
            [self.mainTableView reloadData];
        });
    });
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 刷新表格
    [self.mainTableView reloadData];
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}
- (void)addFooter
{    __unsafe_unretained MySaveViewController *vc = self;
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.mainTableView;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page++;
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是footer
        [self requestPage:Page];
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    _footer = footer;
}
- (void)addHeader
{
    __unsafe_unretained MySaveViewController *vc = self;
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.mainTableView;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        Page = 1;
        //        [self dataSource:StateURL];
        // 模拟延迟加载数据，因此2秒后才调用）
        // 这里的refreshView其实就是header
        [self requestPage:Page];
        [vc performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0];
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
    };
    header.refreshStateChangeBlock = ^(MJRefreshBaseView *refreshView, MJRefreshState state) {
        // 控件的刷新状态切换了就会调用这个block
        switch (state) {
            case MJRefreshStateNormal:
                break;
            case MJRefreshStatePulling:
                break;
            case MJRefreshStateRefreshing:
                break;
            default:
                break;
        }
    };
    [header beginRefreshing];
    _header = header;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.fakeData count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString* cellId = [NSString stringWithFormat:@"cellid%ld",(long)indexPath.row];
    homeVCCell *cell = (homeVCCell*)[tableView dequeueReusableCellWithIdentifier:cellId];
    if(cell == nil){
        cell = [[homeVCCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] ;
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
//        cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellBg.png"]];
    }
    homeModelSupply *model = [self.fakeData objectAtIndex:indexPath.row];
    [cell.futureImg setHidden:NO];
    [cell drawCellView:model];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 104;
}
//添加一项
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[self.rightBtn currentTitle] isEqualToString:@"取消"]) {
        homeModelSupply *dic = [self.fakeData objectAtIndex:indexPath.row];
        [self.selectedArr addObject:dic];
        [self.selectedDic addObject:indexPath];
        //        NSLog(@"Select---->:%@",self.selectedDic);
    }else{
        ProductDetailsViewController *detailsVC = [[ProductDetailsViewController alloc]init];
        detailsVC.supply = [self.fakeData objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:detailsVC animated:YES];
    }
}

//取消一项
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[self.rightBtn currentTitle] isEqualToString:@"取消"]) {
        homeModelSupply *dic = [self.fakeData objectAtIndex:indexPath.row];
        [self.selectedArr removeObject:dic];
        [self.selectedDic removeObject:indexPath];
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
//当 tableview 为 editing 时,左侧按钮的 style
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return selectEditingStyle;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
